//
//  FindEmoticon.swift
//  Weibo
//
//  Created by 孙国强 on 2017/7/7.
//  Copyright © 2017年 孙国强. All rights reserved.
//

import UIKit

class FindEmoticon: NSObject {
    // MARK:- 设计单例对象
    static let shareInstance : FindEmoticon = FindEmoticon()
    
    // MARK:- 表情属性
    private lazy var manager : EmoticonManager = EmoticonManager()
    
    // 查找属性字符串的方法
    func findAttrString(statusText : String?, font : UIFont) -> NSMutableAttributedString? {
        guard let statusText = statusText else {
            return nil
        }
        
        let pattern = "\\[.*?\\]"
        
        guard let regex = try? NSRegularExpression(pattern : pattern, options : []) else {
            return nil
        }
        
        let results = regex.matches(in: statusText, options: [], range: NSRange(location: 0, length: statusText.characters.count))
        
        let attrMStr = NSMutableAttributedString(string: statusText)
        for result in results.reversed() {
            
            let chs = (statusText as NSString).substring(with: result.range)
            
            guard let pngPath = findPngPath(chs: chs) else {
                return nil
            }
            
            let attachment = NSTextAttachment()
            attachment.image = UIImage(contentsOfFile: pngPath)
            attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            let attrImageStr = NSAttributedString(attachment: attachment)
            
            attrMStr.replaceCharacters(in: result.range, with: attrImageStr)
        }
        
        return attrMStr
    }
    
    private func findPngPath(chs : String) -> String? {
        for package in manager.packages {
            for emoticon in package.emoticons {
                if emoticon.chs == chs {
                    return emoticon.pngPath
                }
            }
        }
        
        return nil
    }
}




